//
//  UGCReleaseAddImage.m
//  ZITHER
//
//  Created by weixin on 2018/9/12.
//  Copyright © 2018年 weixn. All rights reservedƒ
//

#import "UGCReleaseAddImage.h"
#import "NetworkEngine.h"
#import "NetworkEngine+imageCloudManager.h"
#import "MainFirst_WX.h"

@implementation UGCReleaseAddImage

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self addImage];
        [self ishidden:0];
        [self addSubview:self.imageSelect];
        @weakify(self);
        [RACObserve(self,arrM) subscribeNext:^(NSMutableArray * x) {
            @strongify(self);
            NSLog(@"x.count = %ld",x.count);
            if (x.count<9) {
                CGFloat imgHeight = (kScreenW-48)/3.0;
                self.imageSelect.frame =  CGRectMake(x.count%3*(imgHeight+10), x.count/3*(imgHeight+10), (kScreenW-48)/3.0, (kScreenW-48)/3.0);
                self.imageSelect.hidden = NO;
            }else if (x.count==9){
                self.imageSelect.hidden = YES;
        }
            
            if (self.arrM.count == 0) {
                self.imageSelect.frame = CGRectMake(0,15, kScreenW-30, (kScreenW-48)/3.0);
            }
            
            for (int i = 0 ; i<self.arrMImage.count; i++) {
                UIImageView *imageView =  self.arrMImage[i];
                if (x.count>i) {
                    imageView.hidden = NO;
                } else {
                    imageView.hidden = YES;
                }
            }

        }];
    }
    return self;
}
//-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//
//    [[self mutableArrayValueForKey:@"arrM"] addObject:@"1"];
//
//}


-(void)ishidden:(NSInteger)index{
    for (int i = 0; i<index; i++) {
        UIImageView *imageV = self.arrMImage[i];
        imageV.hidden = NO;
    }
}

-(void)addImage{

        for (int i = 0; i<9; i++) {
            
            CGFloat imgHeight = (kScreenW-48)/3.0;
            UIImageView *imageV = [[UIImageView alloc]init];
            imageV.frame =  CGRectMake(i%3*(imgHeight+10), i/3*(imgHeight+10), imgHeight, imgHeight);
            imageV.tag = i+100;
            imageV.hidden = YES;
            imageV.contentMode = 2;
            imageV.backgroundColor = [UIColor randomColor];
            [self addSubview:imageV];
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
            @weakify(self);
            [[tap rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
                @strongify(self);
                /* MARK: ================= 弹出头像弹窗 =================*/
                self.selectIndex = imageV.tag;
               
                [self showAlertAction:1];
              
            }];
            
            [imageV addGestureRecognizer:tap];
            
            imageV.userInteractionEnabled = YES;
            //            [imageV sd_setImageWithURL:[NSURL URLWithString:arrM[i]] placeholderImage:nil];
//            [imageV setCornerRadiusWithRadius:8 isMasks:YES];
            imageV.clipsToBounds = YES;
            
            [self.arrMImage addObject:imageV];
        }
}
/* MARK: ================= 上传用户头像图片 =================*/
#pragma mark - 打开图片浏览器
-(void)presentImagePicker:(NSInteger)index{
    TZImagePickerController *picker = [[TZImagePickerController alloc] initWithMaxImagesCount:index delegate:self];
    picker.allowPickingVideo = NO;
    picker.allowTakeVideo = NO;
    @weakify(self);
    [picker setDidFinishPickingPhotosWithInfosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto, NSArray<NSDictionary *> *infos) {
        @strongify(self);
        //1.单张图点击替换   2.

        if (photos.count > 0) {
            
            if (self.selectIndex!=200) {
                UIImageView * imageV = self.arrMImage[self.selectIndex-100];
                imageV.image = photos.firstObject;
                [self.arrM replaceObjectAtIndex:self.selectIndex-100 withObject:photos.firstObject];
            } else {
                for (int i = 0 ; i<photos.count; i++) {
                    
                    [[self mutableArrayValueForKey:@"arrM"] addObject:photos[i]];

                    self.arrMImage[9-index+i].image = photos[i];
                    
                }
            }
            
        }
        
    }];
    
    [self.getNav presentViewController:picker animated:YES completion:nil];
    
}


-(void)showAlertAction:(NSInteger)index{
    @weakify(self);
    QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle:@"取消" style:QMUIAlertActionStyleCancel handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {

    }];
    
   
    QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle:@"拍摄" style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
        @strongify(self);

        [self SystemCamera];
    }];
    
    QMUIAlertAction *action4 = [QMUIAlertAction actionWithTitle:@"从手机相册选择" style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
        //选多张还是单张
        @strongify(self);

        [self presentImagePicker:index];
    }];
   
    
    QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:QMUIAlertControllerStyleActionSheet];
    
    [alertController addAction:action1];
    [alertController addAction:action2];
    [alertController addAction:action4];
    if (self.selectIndex !=200) {
        @weakify(self);
        QMUIAlertAction *action3 = [QMUIAlertAction actionWithTitle:@"删除" style:QMUIAlertActionStyleDestructive handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
            @strongify(self);
            [[self mutableArrayValueForKey:@"arrM"] removeObjectAtIndex:self.selectIndex-100];

            for (int i = 0 ; i<self.arrM.count; i++) {
                self.arrMImage[i].image = self.arrM[i];
            }
        }];
        [action3.button setTitleColor:baseColorForegroundError forState:UIControlStateNormal];
        [alertController addAction:action3];
    }

    
    [alertController showWithAnimated:YES];
    
}
-(NSMutableArray *)arrM{
    if (!_arrM) {
        _arrM = [[NSMutableArray alloc]init];
    }
    return _arrM;
}
-(NSMutableArray<UIImageView *> *)arrMImage{
    if (!_arrMImage) {
        _arrMImage = [[NSMutableArray alloc]init];
    }
    return _arrMImage;
}
-(UIImageView *)imageSelect{
    if (!_imageSelect) {
        _imageSelect = [[UIImageView alloc]init];
        _imageSelect.frame =  CGRectMake(0,15, kScreenW-30, (kScreenW-48)/3.0);
        _imageSelect.hidden = NO;
        _imageSelect.image = [UIImage imageNamed:@"ucg_btn_add"];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
        @weakify(self);
        [[tap rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
            @strongify(self);
            self.selectIndex = 200;
            [self showAlertAction:9-self.arrM.count];
        }];
        [_imageSelect addGestureRecognizer:tap];
        
        _imageSelect.userInteractionEnabled = YES;
//        [_imageSelect setCornerRadiusWithRadius:8 isMasks:YES];
        _imageSelect.clipsToBounds = YES;
        _imageSelect.backgroundColor = [UIColor RGBColorWithR:245 g:245 b:245];
//        _imageSelect.backgroundColor = [UIColor redColor];

        _imageSelect.contentMode = 1;

    }
    return _imageSelect;
}

-(void)SystemCamera{
    UIImagePickerController *pickerCon = [[UIImagePickerController alloc]init];
    pickerCon.sourceType = UIImagePickerControllerSourceTypeCamera;
    pickerCon.allowsEditing = YES;//是否可编辑
    pickerCon.delegate = self;
    [self.getNav presentViewController:pickerCon animated:YES completion:nil];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {//如果是拍照
        UIImage *image;
        //如果允许编辑则获得编辑后的照片，否则获取原始照片
        if (picker.allowsEditing) {
            image=[info objectForKey:UIImagePickerControllerEditedImage];//获取编辑后的照片
        }else{
            image=[info objectForKey:UIImagePickerControllerOriginalImage];//获取原始照片
        }
        
        if (self.selectIndex != 200) {
            UIImageView *imageV = self.arrMImage[self.selectIndex-100];
            imageV.image = image;
            [self.arrM replaceObjectAtIndex:self.selectIndex-100 withObject:image];
        }else{
            
                [[self mutableArrayValueForKey:@"arrM"] addObject:image];
                
                self.arrMImage[self.arrM.count-1].image = image;
            
        }
        //image

        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);//保存到相簿
    }
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    [[self getViewController:[MainFirst_WX class]].tabBarController.tabBar setHidden:YES];

}

/** 清数据 */
-(void)cleanData{
    self.arrM = [[NSMutableArray alloc]init];
    self.arrMImage = [[NSMutableArray alloc]init];
    self.imageSelect.frame = CGRectMake(0,15, kScreenW-30, (kScreenW-48)/3.0);
    self.selectIndex = 0;
    [self addImage];
    [self ishidden:0];
}

@end
